package com.example.stu.kudestu.stu.controller;


import com.example.stu.kudestu.stu.entity.User;
import com.example.stu.kudestu.stu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询所有用户
     * @return
     */
    @RequestMapping("/findAll")
    public List<User> findAll(){

        return userService.findAll();
    }

    /**
     * 根据id查找用户
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public User findById(int id){
        return userService.findUserById(id);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @RequestMapping(value = "/reg",method = RequestMethod.POST)
    public User reg(User user){

        return userService.save(user);
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public User login(String username,String password){
        return userService.login(username,password);
    }

    /**
     * 用户修改
     * @param user
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public User update(User user){
        return userService.save(user);
    }

    /**
     * 用户删除
     * @param id
     */
    @RequestMapping("/delete")
    public void delete(int id){
        userService.delete(id);
    }

    /**
     * 分页查询
     * @param page
     * @param response
     * @return
     */
    @RequestMapping("/page")
    public Page<User> findByPage(Integer page, HttpServletResponse response){

        //解决跨域请求
        response.setHeader("Access-Control-Allow-Origin","*");

        if(page==null || page<=0){
            page = 0;
        }else{
            page -= 1;
        }

        return userService.findByPage(page,5);

    }






}
